#include "ibmsgv_api.h"

char		*g_ibp_ibmsgv_api_kernel_version = IBP_VERSION ;

int IBMSGVReceiver_JSON( struct HttpBuffer *req_buf , DSCDESERIALIZE_JSON_xxx_V *p_unpack_func , void *pv_req_st
			, struct HttpBuffer *rsp_buf , DSCSERIALIZE_JSON_DUP_xxx_V *p_pack_func , void *pv_rsp_st
			, funcIbmsgvTransmain *p_transmain_func , struct IbasAddonFiles *addon_files )
{
	char			*msg = NULL ;
	int			msg_len ;
	
	int			nret = 0 ;
	int			transmain_return = 0 ;
	
	INFOLOGSG( "ibmsgv_api v%s build %s %s ( ibidl v%s, ibutil v%s )" , g_ibp_ibmsgv_api_kernel_version , __DATE__ , __TIME__ , g_ibp_idl_kernel_version , g_ibp_util_kernel_version );
	
	msg = GetHttpBufferBase( req_buf , & msg_len ) ;
	if( msg == NULL )
	{
		ERRORLOGG( "GetHttpBufferBase failed , errno[%d]" , errno );
		return IBP_IBMSGV_ERROR_NO_MESSAGE_BODY;
	}
	
	INFOLOGG( "msg[%d][%.*s]" , msg_len , msg_len , msg );
	msg_len = 0 ;
	nret = p_unpack_func( "GB18030" , msg ,  & msg_len , pv_req_st ) ;
	if( nret )
	{
		ERRORLOGG( "p_unpack_func failed , errno[%d]" , errno );
		return IBP_IBMSGV_ERROR_UNPACK_MESSAGE;
	}
	else
	{
		INFOLOGG( "p_unpack_func ok" );
	}
	
	transmain_return = p_transmain_func( pv_req_st , pv_rsp_st , addon_files ) ;
	if( transmain_return )
	{
		ERRORLOGG( "p_transmain_func failed[%d]" , transmain_return );
		return IBP_IBMSGV_ERROR_TRANSMAIN;
	}
	else
	{
		INFOLOGG( "p_transmain_func ok" );
	}
	
	if( IBASGetResponseFlag() == 0 )
	{
		msg = NULL ;
		msg_len = 0 ;
		nret = p_pack_func( pv_rsp_st , "GB18030" , & msg , NULL , & msg_len ) ;
		if( nret )
		{
			ERRORLOGG( "p_pack_func failed , errno[%d]" , errno );
			return IBP_IBMSGV_ERROR_PACK_MESSAGE;
		}
		else
		{
			INFOLOGG( "p_pack_func ok" );
			INFOLOGG( "msg[%.*s]" , msg_len , msg );
		}
		
		nret = MemcatHttpBuffer( rsp_buf , msg , msg_len ) ;
		free( msg );
		if( nret )
		{
			ERRORLOGG( "MemcatfHttpBuffer failed , errno[%d]" , errno );
			return IBP_IBMSGV_ERROR_A_S(nret);
		}
	}
	
	return transmain_return;
}

int IBMSGVReceiver_JSON_SendResponseAhead( DSCSERIALIZE_JSON_DUP_xxx_V *p_pack_func , void *pv_rsp_st )
{
	char			*msg = NULL ;
	int			msg_len ;
	
	int			nret = 0 ;
	
	msg = NULL ;
	msg_len = 0 ;
	nret = p_pack_func( pv_rsp_st , "GB18030" , & msg , NULL , & msg_len ) ;
	if( nret )
	{
		ERRORLOGG( "p_pack_func failed , errno[%d]" , errno );
		return IBP_IBMSGV_ERROR_PACK_MESSAGE;
	}
	else
	{
		INFOLOGG( "p_pack_func ok" );
		INFOLOGG( "msg[%.*s]" , msg_len , msg );
	}
	
	nret = MemcatHttpBuffer( IBASGetResponseBody() , msg , msg_len ) ;
	free( msg );
	if( nret )
	{
		ERRORLOGG( "MemcatHttpBuffer failed , errno[%d]" , errno );
		return IBP_IBMSGV_ERROR_A_S(nret);
	}
	
	nret = IBASSendResponseAhead() ;
	if( nret )
	{
		ERRORLOGG( "IBASSendResponseAhead failed[%d]" , nret );
		return nret;
	}
	else
	{
		INFOLOGG( "IBASSendResponseAhead ok" );
	}
	
	return 0;
}

